<template>
  <div class="g-btmbar" ref="music_bar"  @mouseenter="!latch_falg && enter()">
    <div
      :style="{'top':top +'px' ,  'visibility': 'visible'}"
      class="m-playbar m-playbar-lock"
      @mouseleave="!latch_falg && leave()"
    >
      <div class="updn">
        <div class="left f-fl">
          <a href="javascript:;" :class="['btn' ,{'btn_close':latch_falg , 'btn_open':!latch_falg}]" @click.stop="latch_falg = !latch_falg"></a>
        </div>
        <div class="right f-fl"></div>
      </div>
      <div class="bg"></div>
      <div class="hand" title="展开播放条"></div>
        <!-- 播放 切换 滑动条...等中间的盒子 -->
      <div class="wrap" id="g_player" style="margin-left: -498.5px">
        <div class="btns">
          <a href="javascript:;" class="prv" title="上一首(ctrl+←)" @click="last" >上一首</a>
          <a href="javascript:;" title="播放" class="btn_play"  @click="play(false)" v-if="flag">播放</a>
          <a href="javascript:;" title="暂停" class="btn_stop"  @click="play(true)" v-if="!flag">暂停</a>
          <a href="javascript:;" class="nxt" title="下一首(ctrl+→)" @click="next">下一首</a>
        </div>
        <div class="head j-flag" >
          <img :src="musicIDS[msc_num].al.picUrl" v-if="musicIDS.length && musicIDS[msc_num].al">
          <img :src="musicIDS[msc_num].coverUrl" v-else-if="musicIDS.length && musicIDS[msc_num].coverUrl">
          <img src="https://s4.music.126.net/style/web2/img/default/default_album.jpg" v-else>
          <a class="mask"></a>  
        </div>
        <div class="play" ref="father">
          <div class="j-flag words">
            <a href="javascript:;" class="f-thide name fc1 f-fl" title="歌名"
              >
              {{musicIDS.length? musicIDS[msc_num].name :null}}
            </a>
            <span class="by f-thide f-fl">
              <span v-if="musicIDS.length && musicIDS[msc_num].ar">
                <a href="javascript:;" title="歌手" v-for="(Aitem , Aindex) in musicIDS[msc_num].ar" :key="Aindex">{{Aitem.name}}<slot v-if="Aindex < musicIDS[msc_num].ar.length -1">/</slot> </a>
              </span>
               <span v-if="musicIDS.length && musicIDS[msc_num].dj">
                <a href="javascript:;" title="歌手">{{musicIDS[msc_num].dj.nickname}}</a>
              </span>
            </span>
          </div>
          <div class="m-pbar" ref="scollbar">
            <div class="barbg j-flag">
              <div class="rdy" :style="{'width':cache_bar+'px'}"></div>
              <div class="cur" :style="{'width':songvalue+'%'}">
                <span class="btn f-tdn f-alpha" @mousedown="move"><i :class="{show :loading}"></i> </span>
              </div>
            </div>
            <span class="j-flag time" v-if="musicIDS.length">
              <em>{{ songChange_Time }}</em>
              /{{musicIDS[msc_num].dt | DT}}
            </span>
            <audio ref="play" :src="songUrl"></audio>
          </div>
        </div>
        <div class="oper f-fl">
          <a href="javascript:;" class="icn icn-pip">画中画歌词</a>
          <a href="javascript:;" class="icn icn-add j-flag" @click.stop="sc($event)">收藏</a>
        </div>
        <div class="ctrl f-fl f-pr j-flag" ref="volumeBox">
          <div class="m-vol" v-show="v_flag" >
            <div class="block">
              <el-slider
                vertical
                height="100px"
                v-model="value"
                @input="volume_bar"
              >
              </el-slider>
            </div>
          </div>
          <a
            href="javascript:;"
            class="icn icn-vol"
            title="音量"
            @click="v_flag = !v_flag"
          ></a>
          <a
            href="javascript:;"
            :class="['icn' ,{'icn-loop':repeat_icn , 'icn-shuffle':!repeat_icn}]"
            title="循环"
            @click="repeat_icn = !repeat_icn"
          ></a>
          <span class="add f-pr">
            <span class="tip" v-show="prompt_flag">已添加到播放列表</span>
            <a
              href="javascript:;"
              title="播放列表"
              data-action="panel"
              class="icn icn-list s-fc3"
              @mousedown="menuFlag"
              >{{musicIDS.length ? musicIDS.length: 0}}</a
            >
          </span>
        </div>
      </div>
       <playMenu  :data="musicIDS" :num='msc_num'  :CT ='currentTime' v-show="menu_flag"></playMenu> 
    </div>
  </div>
</template>
<script>
import { getSongDetial } from "../../network/play";
import { playSong } from "../../network/play";
import {Time} from '../tool/tool'
import {check_music} from '../../network/play'
import  playMenu from './playmusic_menu'
export default {
  data() {
    return {
      top: -7,   //整个音乐播放器上下滑动
       latch_falg:false, //控制是否锁定播放器滑动
       setInter:null, //定时器
       enter_flag:false, //鼠标在播放器上 停止隐藏动画
       flag: false, //播放图标
       songUrl: null, //音乐的url
       songChange_Time: '00:00', //音乐变化的时长【00：13】
       currentTime:0,  //歌曲播放音频的当前位置（以秒计）
       songvalue: 0, //播放音乐滚动条的长度 
       cache_bar:0,
       value: 50, //音量滑动的值
       ud:true,   //拖动滚动条
       repeat_icn: true, //随机/ 循环播放按钮
       v_flag: false, //音量盒子的显示与否
       musicIDS: [], //音乐数据集合
       msc_num: 0, // 控制音乐的索引
       prompt_flag: false, // 音乐加入列表时的提示盒子
       loading : true, //加载按钮
       menu_flag : false, //音乐菜单
    };
  },
  components:{
       playMenu
  },
  filters:{
      DT(value){
       return   Time(value)
      }
  },
  methods: {
   // 播放器向上滑动
    enter(flag){
      var start = 7
      var end = 53
      if(this.top == -7 && !this.menu_flag){
        var setInter = setInterval(() => {
          var step = Math.ceil((end - start) / 2)
          start += step
          if(start >= end ){
            clearTimeout(setInter)
             if(flag){
                  this.leave()
                }
           }
        this.top = -start
        }, 30);
      }
    },
    //播放器向下滑动
    leave(){
      var start = 53
      var end = 7
      setTimeout(() => {
        if(this.top == -53 && !this.menu_flag){
        var setInter = setInterval(() => {
          var step = Math.ceil((start - end) / 5)
          start -= step
          if(start <= end){
            clearTimeout(setInter)
          } 
         this.top = -start
        }, 30);
      }
      }, 1000);
    },
    menuFlag(){
      //打开歌词菜单
      this.menu_flag = !this.menu_flag
      this.$nextTick(() => {
         if(this.menu_flag){
           this.$children[1].queryTop()
         }
      })

    },
    repeat_flag() {
      //true:循环  false ：随机
      if (this.repeat_icn) {    //循环
        return this.msc_num;
      } else {
        var length = this.musicIDS.length - 1;  //随机
        return  Math.floor(Math.random() * length);
      }
    },
    prompt_box() {
      //新歌曲进来的提示盒子
      this.prompt_flag = true;
      setTimeout(() => {
        this.prompt_flag = false;
      }, 1000);
    },
    del_item(index){
      //点击删除的音乐
      if (index == this.msc_num) {
      this.msc_num = index
       if(this.msc_num >= this.musicIDS.length -1) this.msc_num = 0
       this.musicIDS.splice(index,1)
        sessionStorage.setItem("num", this.msc_num);
        sessionStorage.setItem('play_ids',JSON.stringify(this.musicIDS))
        if(!this.musicIDS.length){
            this.songUrl = " "
            this.songvalue = 0
            sessionStorage.setItem("musicURL", this.songUrl);
            return
        } 
       this.result_mscURL(this.musicIDS[this.msc_num].id)
      }

      if(index < this.msc_num){
           this.msc_num --
           this.musicIDS.splice(index,1)
            sessionStorage.setItem("num", this.msc_num);
           sessionStorage.setItem('play_ids',JSON.stringify(this.musicIDS))
      }

      if(index > this.msc_num){
           this.musicIDS.splice(index,1)
           sessionStorage.setItem('play_ids',JSON.stringify(this.musicIDS))
      }
    },
    del_all(){
       //删除所有音乐
        this.musicIDS.splice(0,this.musicIDS.length)
        sessionStorage.setItem('play_ids',null)
        this.songUrl = " "
        this.songvalue = 0
    },
    selec_music(index){
       //菜单选中的音乐
       this.flag = true
       this.msc_num = index
       sessionStorage.setItem("num", this.msc_num);
      this.result_mscURL(this.musicIDS[this.msc_num].id);
    },
    last() {
      //上一首
      this.flag = true
      var m = true;
      if (m) {
        m = false;
        this.msc_num = this.repeat_flag();
        this.msc_num--;
        if (this.msc_num < 0) {
          this.msc_num = this.musicIDS.length -1;
        }
        sessionStorage.setItem("num", this.msc_num);
        this.result_mscURL(this.musicIDS[this.msc_num].id);
        m = true;
      }
    },  
    next() {
      //下一首
      this.flag = true
      var m = true;
      if (m) {
        //节流
        m = false;
        this.msc_num = this.repeat_flag();
        this.msc_num ++
        if (this.msc_num >= this.musicIDS.length) {
          this.msc_num = 0;
        }
        sessionStorage.setItem("num",this.msc_num);
        this.result_mscURL(this.musicIDS[this.msc_num].id);
        m = true;
      }
    },
    sc(e) {   //收藏
      if (!this.$store.state.userId) {
      this.$login.show(e.pageY - 500)
        return;
      }
      this.menu_flag  = false
      this.$SC.isshow( e.pageY-500, this.musicIDS[this.msc_num]);
    },
    volume_bar() {  //调节音量大小
      this.$refs.play.volume = this.value / 100;
    },
    move(e) {      //拖动滚动条
      var _this = this;
      var play  = this.$refs.play;
      var scollbar_Left = this.$refs.scollbar.getBoundingClientRect().left
      this.ud = false
      this.$refs.father.onmousemove = function (e) {
         var newX = ((e.pageX - scollbar_Left) / 466) * 100;
        if (newX <= 0) {
              newX = 0
        } else if (newX >= 100) {
           newX =  100
        }
          _this.songvalue = newX
          _this.songChange_Time = _this.setTime(play.duration/100 *_this.songvalue); //拖动滚动条时同步旁边的时间帧
      }
      document.onmouseup =function (e){
        e.stopPropagation();
        _this.ud = true
         _this.$refs.father.onmousemove = document.onmouseup = null;
         _this.currentTime = play.currentTime =play.duration/100 *_this.songvalue
        _this.$children[1].drag(_this.currentTime )
      } 
    },
    play(flag) {
      //true播放 false暂停  默认是false暂停
      this.flag = flag
       if (this.flag) {
          this.$refs.play.play();
          this.setscrollbar();
       } else {
        this.$refs.play.pause();
       }
    },
    check_repeat(ID){ //检查过来的单曲是否在当前列表已存在
          var arr = this.musicIDS.findIndex(item =>{
               return item.id === ID.id
           }) 
          if(arr == -1){
            console.log("可以添加")
            this.musicIDS.push(ID)
            this.msc_num = this.musicIDS.length -1
             sessionStorage.setItem("play_ids", JSON.stringify( this.musicIDS));
            sessionStorage.setItem("num", this.msc_num);
             this.result_mscURL(this.musicIDS[this.msc_num].id)
          }else{
            console.log("列表里已经存在索引是"+arr)
            this.selec_music(arr)
          }
       
    },
    result_mscURL(id) {    //获取歌曲url
       this.enter(true)
       playSong(id).then((res) => {   //向服务器请求
          this.$refs.play.currentTime = 0
          this.songUrl = res.data.data[0].url
          this.songLoad();
        });
        this.$nextTick(() => {
           this.$children[1]. res_lyric(id)
        })
    },  
    songLoad() {
      //播放之前的操作【2】
       this.loading = true
       this.$refs.play.addEventListener("canplay", () => {
        if(this.flag){
           this.play(true)
        }
      });
    },
    setscrollbar() {
      //滚动条 向前滚动【3】
          var _this = this;
           var dom = this.$refs.play;
         dom.addEventListener("timeupdate", function () {
            if(this.buffered.length != 0){
                _this.cache_bar = (this.buffered.end(0)/this.duration)*466  
            }
           if (_this.ud) {
             _this.currentTime = dom.currentTime
             _this.songChange_Time = _this.setTime(dom.currentTime);   //歌曲播放的当前时间
              _this.songvalue = (dom.currentTime / this.duration) * 100 //dom.currentTime当前播放位置 audioAPI
           }
       });
    },
    setTime(time) {   //转换时间函数【4】
      let min =
        Math.floor(time / 60).toFixed(0) > 10
          ? Math.floor(time / 60).toFixed(0)
          : "0" + Math.floor(time / 60).toFixed(0); // 分钟
      let second = time % 60 > 9 ? time % 60 :
       "0" + (time % 60); // 秒数
      let length = (min + ":" + second).slice(5);
      return (min + ":" + second).replace(length, " ");
   }
  },
  watch: {
    "$store.state.music_id":function(id){  //监听传过来的歌曲/歌单数据
    this.prompt_box()
    this.loading = false
      if (id.name == '歌单') {
        this.flag =true
        this.musicIDS = []
        this.msc_num = 0
        this.musicIDS = id.ids
        this.result_mscURL(this.musicIDS[this.msc_num].id)
      }
      if (id.name == "歌曲") {
         this.flag =true
         this.check_repeat(id.ids)
         return
      }
      if(id.name == '专辑'){
        this.flag =true
        this.musicIDS = []
        this.msc_num = 0
        this.musicIDS = id.ids
        this.result_mscURL(this.musicIDS[this.msc_num].id)
      } 
      if(id.name == '电台'){
         this.flag =true
         this.musicIDS.push(id.ids)
        this.msc_num = this.musicIDS.length -1
        this.result_mscURL(this.musicIDS[this.msc_num].id)
      } 
      sessionStorage.setItem("play_ids", JSON.stringify( this.musicIDS));
      sessionStorage.setItem("num", this.msc_num);
      this.menu_flag = false
    },
    songvalue(v) {
      ///音乐结束的时候触发的操作
      if (v == 100) {
        this.next();
      }
    },
  },
  created(){
      if(sessionStorage.play_ids && sessionStorage.num){
          this.musicIDS = JSON.parse(sessionStorage.getItem("play_ids")) 
          this.msc_num = sessionStorage.num
          this.result_mscURL(this.musicIDS[this.msc_num].id)
      }
  },
  mounted(){
     var _this = this
   document.addEventListener('click' ,function(e){
       e.stopPropagation()
         if(e.target.className != 'icn icn-vol'){
           _this.v_flag = false
         }
   }) 
  }
};
</script>
<style scoped>
@import url("./playmusic_style/play.css");
</style>
 